package com.novunda.platform.common.dialects.shiro.processor;

import com.novunda.platform.common.dialects.shiro.ShiroFacade;
import com.novunda.platform.common.dialects.shiro.ShiroUtils;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;

/**
 * @author linfeng
 * @since 2016/9/12
 */
public class HasAnyRolesElementProcessor extends AbstractElementProcessor {

    private static final String TAG_NAME = "hasAnyRoles";
    private static final int PRECEDENCE = 1200;

    public HasAnyRolesElementProcessor(final String dialectPrefix) {
        super(TemplateMode.HTML, // This processor will apply only to HTML mode
                dialectPrefix,     // Prefix to be applied to name for matching
                TAG_NAME,          // Tag name: match specifically this tag
                true,              // Apply dialect prefix to tag name
                null,              // No attribute name: will match by tag name
                false,             // No prefix to be applied to attribute name
                PRECEDENCE);       // Precedence (inside dialect's own precedence)
    }

    @Override
    protected void doShiroHandler(ITemplateContext context, IProcessableElementTag tag,
                                  String permissionValue, IElementTagStructureHandler structureHandler) {

        final String[] roleArray = permissionValue.split(",");
        if (!ShiroUtils.arrayIsNotBlank(roleArray)) {
            structureHandler.removeElement();
        }
        if (!ShiroFacade.hasAnyRoles(roleArray)) {
            structureHandler.removeElement();
        }

    }

}
